package com.liang.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.liang.common.utils.R;
import com.liang.gulimall.cart.feign.ProductServiceFeign;
import com.liang.gulimall.cart.interceptor.CartInterceptor;
import com.liang.gulimall.cart.service.CartService;
import com.liang.gulimall.cart.vo.Cart;
import com.liang.gulimall.cart.vo.CartItem;
import com.liang.gulimall.cart.vo.SkuInfoVo;
import com.liang.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    ProductServiceFeign productServiceFeign;
    @Autowired
    StringRedisTemplate redisTemplate;
    private static final String CART_PREFIX = "cart:";
    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());//购物车中是否存在，存在改变数量就行

        if (!StringUtils.isEmpty(o)) {
            CartItem cartItem = JSONObject.parseObject(o, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            String toRedisJson = JSONObject.toJSONString(cartItem);
            cartOps.put(skuId.toString(), toRedisJson);
            return cartItem;
        }
        CartItem cartItem = new CartItem();
        CompletableFuture<Void> runAsync1 = CompletableFuture.runAsync(() -> {
            R info = productServiceFeign.info(skuId);
            SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
            });
            cartItem.setCheck(true);
            cartItem.setCount(num);
            cartItem.setImage(skuInfo.getSkuDefaultImg());
            cartItem.setPrice(skuInfo.getPrice());

            cartItem.setTitle(skuInfo.getSkuTitle());
            cartItem.setSkuId(skuId);
        }, executor);
        CompletableFuture<Void> runAsync2 = CompletableFuture.runAsync(() -> {
            List<String> skuSaleAttr = productServiceFeign.skuSaleAttr(skuId);
            cartItem.setSkuAttrValues(skuSaleAttr);
        }, executor);
        CompletableFuture.allOf(runAsync1, runAsync2).get();
        String s = JSONObject.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);
        return cartItem;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        return JSONObject.parseObject(o, CartItem.class);
    }

    @Override
    public Cart getCartInfo() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //登录了
            List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());//临时购物车
            if (cartItems != null) {//临时购物车还没合并，开始合并
                for (CartItem cartItem : cartItems) {
                    //addToCart(cartItem.getSkuId(),cartItem.getCount());//会远程调用，可能会影响性能,可以直接添加到Redis
                    BoundHashOperations<String, Object, Object> cartOps = getCartOps();
                    String o = (String) cartOps.get(cartItem.getSkuId().toString());//在线购物车中是否存在，存在改变数量就行
                    if (!StringUtils.isEmpty(o)) {
                        CartItem cartItemExit = JSONObject.parseObject(o, CartItem.class);
                        cartItemExit.setCount(cartItemExit.getCount() + cartItem.getCount());
                        cartOps.put(cartItem.getSkuId().toString(), JSONObject.toJSONString(cartItemExit));
                    } else {
                        cartOps.put(cartItem.getSkuId().toString(), JSONObject.toJSONString(cartItem));
                    }
                }
                clearCart(CART_PREFIX + userInfoTo.getUserKey());
            }
            List<CartItem> list = getCartItems(CART_PREFIX + userInfoTo.getUserId());//临时和在线购物车数据
            cart.setItems(list);
        } else {
            //没有登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKet) {
        redisTemplate.delete(cartKet);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSONObject.toJSONString(cartItem));

    }

    @Override
    public void setCountItem(Long skuId, Integer count) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(count);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSONObject.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCheckedItem() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo == null) {
            return null;
        }
        String cartKet = CART_PREFIX + userInfoTo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKet);
        //获取被选中的
        List<CartItem> collect = cartItems.stream().map(cartItem -> {
            BigDecimal price = productServiceFeign.getPrice(cartItem.getSkuId());
            //更新最新价格
            cartItem.setPrice(price);
            return cartItem;
        }).filter(item -> item.getCheck()).collect(Collectors.toList());

        return collect;
    }

    /**
     * 操作哪个购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        String cartKet = "";
        if (userInfoTo.getUserId() != null) {
            //登录了
            cartKet = CART_PREFIX + userInfoTo.getUserId();
        } else {
            //没有登录
            cartKet = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKet);

        return hashOps;
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOpsUserKey = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOpsUserKey.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(obj -> {
                CartItem cartItem = JSONObject.parseObject((String) obj, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
